/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BusquedaProveedor.java
 *
 * Created on Feb 22, 2010, 8:23:05 PM
 */

package edu.fca.ui.search;

import edu.fca.beans.ProfesorBean;
import edu.fca.ui.tools.ComponentManager;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import logic.services.ProfesorServices;

/**
 *
 * @author Romms
 */
public class SearchProfesorUI extends javax.swing.JDialog {

    /** Creates new form BusquedaProveedor */

    private ArrayList<ProfesorBean> profesores;
    private String cols[] ={"Codigo","Nombre","Apellido Paterno","Apellido Materno"};

    private ProfesorBean profesor;
    DefaultTableModel model;


    public SearchProfesorUI(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        ComponentManager.centerJDialog(this);

        this.profesores= ProfesorServices.getInstance().getProfesores();
        model = new DefaultTableModel(cols,this.profesores.size());
        profesor= new ProfesorBean();
        
        this.updateTable();

    }
    private void updateTable(){
            this.txtCriteria.setText("");
            
            this.tblProfesores.setModel(model);
            this.fillTable(this.profesores);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtCriteria = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblProfesores = new javax.swing.JTable(){
			  public boolean isCellEditable(int rowIndex, int colIndex) {
					return false;   //Disallow the editing of any cell
			  }
		};

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Busca Profesor");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                formKeyReleased(evt);
            }
        });

        txtCriteria.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCriteriaKeyReleased(evt);
            }
        });

        jLabel1.setText("Criterio:");

        tblProfesores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblProfesores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblProfesoresMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblProfesores);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtCriteria, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCriteria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtCriteriaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCriteriaKeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_ESCAPE){
            this.dispose();
        }
        if(this.txtCriteria.getText().compareTo("")==0){
            this.fillTable(this.profesores);
            return;
        }

        ArrayList <ProfesorBean> profesoresFound=this.foundCriteria(this.txtCriteria.getText().trim());

        if(profesoresFound.size()==0){
            this.emptyTable();
        }else{
            this.emptyTable();
            this.fillTable(profesoresFound);
        }
    }//GEN-LAST:event_txtCriteriaKeyReleased

    private void tblProfesoresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblProfesoresMouseClicked
        if (evt.getClickCount() == 2) {
            if(this.tblProfesores.getSelectedRow()==-1 || tblProfesores.getValueAt(this.tblProfesores.getSelectedRow(), 0)==null){
                this.dispose();
                return;
            }
            this.setFieldsProveedor();
            this.dispose();
            this.setVisible(false);
        }
    }//GEN-LAST:event_tblProfesoresMouseClicked

    private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased

    }//GEN-LAST:event_formKeyReleased

    private void setFieldsProveedor(){
        int row=this.tblProfesores.getSelectedRow();

        profesor.setCodigo(tblProfesores.getValueAt(row,0).toString());
        profesor.setNombre(tblProfesores.getValueAt(row,1).toString());
        profesor.setApellidoP(tblProfesores.getValueAt(row,2).toString());
        profesor.setApellidoM(tblProfesores.getValueAt(row,3).toString());

    }

    private void emptyTable(){
        for(int row=0;row<this.profesores.size();row++){
            for(int col=0;col<profesores.size();col++){

                model = new DefaultTableModel(cols,0);
                this.tblProfesores.setModel(model);
            }
        }
    }
    private ArrayList <ProfesorBean>foundCriteria(String criteria){
        int rowsInTable=this.profesores.size();

        ArrayList <ProfesorBean> profesoresDetailFound= new ArrayList();

        for(int indexCount=0;indexCount<rowsInTable;indexCount++){
            if(this.existsInRow(indexCount, criteria.toLowerCase()))
                profesoresDetailFound.add(this.profesores.get(indexCount));
        }

        return profesoresDetailFound;
    }

    private void fillTable(ArrayList <ProfesorBean> info){

        model = new DefaultTableModel(cols, info.size());
        this.tblProfesores.setModel(model);
        int tam=info.size()-1;
        for(int fila=0;fila<=tam;fila++){
                this.tblProfesores.setValueAt(info.get(fila).getCodigo(), fila, 0);
                this.tblProfesores.setValueAt(info.get(fila).getNombre(), fila, 1);
                this.tblProfesores.setValueAt(info.get(fila).getApellidoP(), fila, 2);
                this.tblProfesores.setValueAt(info.get(fila).getApellidoM(), fila, 3);
        }
    }

    private boolean existsInRow(int row, String criteria){
        String codigo=String.valueOf(this.profesores.get(row).getCodigo());
        String nombre=String.valueOf(this.profesores.get(row).getNombre());
        String apellidoP=String.valueOf(this.profesores.get(row).getApellidoP());
        String apellidoM=String.valueOf(this.profesores.get(row).getApellidoM());

       if(codigo.toLowerCase().startsWith(criteria))return true;
       if(nombre.toLowerCase().startsWith(criteria))return true;
       if(apellidoP.toLowerCase().startsWith(criteria))return true;
       if(apellidoM.toLowerCase().startsWith(criteria))return true;


       return false;
    }

    public ProfesorBean getSelectedProfesor(){
        return profesor;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SearchProfesorUI dialog = new SearchProfesorUI(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblProfesores;
    private javax.swing.JTextField txtCriteria;
    // End of variables declaration//GEN-END:variables

}

